package cn.songtx.iot.config;

import cn.songtx.iot.pojo.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/*
 * 全局异常处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    /*
     * 异常处理方法，一旦Controller发生此异常就会被拦截到
     * 细化添加失败后的返回信息
     */
    @ExceptionHandler({Exception.class})
    public Result exceptionHandler(Exception exception) {
        String cause = exception.getCause().toString();
        if (cause.contains("Duplicate entry")) {
            String[] s = cause.split(" ");
            String msg = s[3] + "已存在!";
            return Result.error(msg);
        } else if (cause.contains("doesn't have a default value")) {
            String[] s = cause.split(" ");
            String msg = s[2] + "没有值!";
            return Result.error(msg);
        } else if (cause.contains("Data too long for column")) {
            String[] s = cause.split("'");
            String msg = s[1] + "超过字段长度!";
            return Result.success(msg);
        }
        return Result.error(exception.toString());
    }
}
